package com.wanwanbookstore.servlet;

import com.wanwanbookstore.dao.BookDAO;
import com.wanwanbookstore.entity.Book;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class BookDetailServlet extends HttpServlet {
    private BookDAO bookDAO = new BookDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取图书ID参数
        String bookIdStr = request.getParameter("id");
        
        if (bookIdStr == null || bookIdStr.isEmpty()) {
            // 如果没有提供ID，重定向到图书列表页面
            response.sendRedirect(request.getContextPath() + "/books");
            return;
        }
        
        try {
            int bookId = Integer.parseInt(bookIdStr);
            
            // 根据ID获取图书详情
            Book book = bookDAO.getBookById(bookId);
            
            if (book == null || book.isDeleted()) {
                // 如果图书不存在或已删除，显示错误信息
                request.setAttribute("errorMessage", "图书不存在或已下架");
                request.getRequestDispatcher("index.jsp").forward(request, response);
                return;
            }
            
            // 获取相关推荐图书（同分类的其他图书）
            List<Book> relatedBooks = bookDAO.getBooksByCategory(book.getCategory(), 1, 6);
            
            // 将图书信息和推荐图书设置到请求属性中
            request.setAttribute("book", book);
            request.setAttribute("relatedBooks", relatedBooks);
            
            // 转发到图书详情页面
            // 注意：这里假设存在book_detail.jsp页面，如果不存在需要创建
            request.getRequestDispatcher("book_detail.jsp").forward(request, response);
            
        } catch (NumberFormatException e) {
            // 如果ID格式不正确，重定向到图书列表页面
            request.setAttribute("errorMessage", "无效的图书ID");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
}